﻿namespace Microsoft.Extensions.DependencyInjection;

public static class TokenExtension
{
    public static bool IsAssignableFrom<T>(this Type t) =>
        typeof(T).IsAssignableFrom(t);
    
    /// <summary>
    /// 判断是否继承自 <see cref="ISingletonDependency"/> <see cref="IScopedDependency"/> <see cref="ITransientDependency"/>
    /// </summary>
    /// <param name="type"></param>
    /// <returns></returns>
    public static bool IsAssignableModule(this Type type)
    {
        var disabledInjectAttribute = type.GetCustomAttribute<DisabledInjectAttribute>();

        if (disabledInjectAttribute?.Disabled == true)
        {
            return false;
        }

        if (type.Attributes.HasFlag(TypeAttributes.Abstract) || type.Attributes.HasFlag(TypeAttributes.Interface))
        {
            return false;
        }

        if (typeof(ISingletonDependency).IsAssignableFrom(type) ||
            typeof(IScopedDependency).IsAssignableFrom(type) ||
            typeof(ITransientDependency).IsAssignableFrom(type))
        {
            return true;
        }

        return false;
    }
    
    /// <summary>
    /// 获取注入方法相对应的需要注入的标记
    /// </summary>
    /// <param name="type"></param>
    /// <returns></returns>
    public static Type? GetDependencyType(this Type type)
    {
        // 得到类型的注入标记
        var assignServices = type.GetCustomAttribute<AssignServicesAttribute>();
        // 通过名称匹配注入的类型
        return assignServices == null ? type.GetInterfaces().Where(x => x.Name.EndsWith(type.Name))?.FirstOrDefault() : type.GetInterfaces().Where(x => x == assignServices.Type)?.FirstOrDefault();
    }
}